import socket
import sqlite3
import time
import json

# 连接数据库
conn = sqlite3.connect('mydb.db')
cursor = conn.cursor()


# 创建表
cursor.execute('''
    CREATE TABLE IF NOT EXISTS state (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        states TEXT,
        timestamp REAL
    )
''')
# 提交命令
conn.commit()


# 创建socket对象,并指定使用IPv4和TCP协议
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 连接服务器
host = '114.215.65.250'
port = 4509
sock.connect((host, port))

# 发送登陆命令
login_cmd = 'KEY:farsight8+123456'
sock.sendall(login_cmd.encode())

# 接收服务器响应
respond = sock.recv(1024).decode()  
print(respond)

if 'login-success' in respond:
    print('登陆成功')
    # 使用缓冲区处理数据分包
    buffer = ""
    # 易监控返回的信息
    while True:
        data = sock.recv(1024).decode(errors='ignore')

        """buffer += data
        # 处理缓冲区中的所有完整消息
        while '+' in buffer and '}' in buffer:
            # 找到第一条完整消息的结束位置
            end_index = buffer.find('}') + 1
            if end_index <= 0:
                break

            full_msg = buffer[:end_index]
            buffer = buffer[end_index:]

        try:
            # 使用更健壮的分割方法
            if '+' not in full_msg:
                continue
            prefix_part, json_str = full_msg.split('+', 1)
            # 修复可能的JSON格式问题
            json_str = json_str.strip()
            if not json_str.startswith('{'):
                # 查找第一个{
                start_index = json_str.find('{')
                if start_index > 0:
                    json_str = json_str[start_index:]
                
            json_data = json.loads(json_str)
            device_id = prefix_part.split(':')[1] if ':' in prefix_part else 'unknown'

        # 解析数据
        # prefix_part, json_str = data.split('+', 1)
        # device_id = prefix_part.split(':')[1]
        # json_data = json.loads(json_str)


            # 存储数据
            cursor.execute("INSERT INTO state (states, timestamp) VALUES (?, ?)", (full_msg, time.time()))
            conn.commit()

            # 更新数据
            cursor.execute("UPDATE sta SET states = ? where name = ?",(prefix_part, device_id))

            # 打印完整消息
            print(f"处理成功: {device_id} | {json_data}")

        except (json.JSONDecodeError, IndexError, ValueError) as e:
            print(f"解析错误: {e} | 原始数据: {full_msg}")
            # 记录错误数据
            cursor.execute("INSERT INTO state (states, timestamp) VALUES (?, ?)", (f"ERROR:{str(e)} | DATA:{full_msg}", time.time()))
"""
        if not data:
            print('接收信息失败')
            break
        print(data)
        if "logout" in data:
            print('退出登录')
            break
else:
    print('登陆失败')

cursor.execute("select * from state")
# 打印所有数据
for row in cursor.fetchall():
    print(row)

# 关闭套接字
sock.close()

# 关闭数据库
cursor.close()
conn.close()
